<template>
  <div>
    <modal-view title="视频挂载卡券" ref="modalViewRef" width="700px" :before-submit="beforeSubmit" @close="close">
      <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules" label-position="left" size="small">
        <el-form-item label="标题" prop="Title">
          <el-input v-model="formData.Title" placeholder="显示标题"></el-input>
        </el-form-item>

        <data-view v-loading="rightLoading" style="height:400px" v-model="dataList" v-model:searchValue="searchValue"
          :header-btn="['search']" :current-page="currentPage" :page-size="pageSize" :total="dataTotal" @search="onSearch"
          @update:current-page="onUpdateCurrentPage">
          <template #content="{ dataItem }">
            <e-card-rule-card :class="{
              'page-ecard-select': selectEcardId == dataItem.Id,
            }" style="margin:5px;cursor: pointer;" :stock="stocksMap.get(dataItem.Id)" :card-data="dataItem"
              @click="selectEcardId = dataItem.Id">
            </e-card-rule-card>
          </template>
        </data-view>
      </el-form>
    </modal-view>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { queryGet } from "@/utils/api";
import { CmpDataClass } from "@/model/Cmp";
export default defineComponent({
  name: "DyVideoECardRuleModalView",
})
</script>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ModalView from "@/components/ModalView";
import { appAction } from "@/store/app";
import { docType, ECardRuleDataClass, VALID_TYPE } from "@/model/ECardRule";
import { request } from "@/utils/axios";
import CmpCard from "@/views/pages/Cmp/CmpCard.vue";
import SelectLoad from "@/components/SelectLoad";
import DataView from "@/components/DataView";
import ECardRuleCard from "@/views/pages/ECardRule/ECardRuleCard.vue"

let emit = defineEmits<{
  (e: "close"): void;
  (e: "submit", para: {
    videoId: string,
    title: string
  }): void
}>()

/**
 * 弹框
 */
let modalViewRef = ref();

/**
 * 表单
 */
let formRef = ref();

/**
 * 选择的卡券id
 */
let selectEcardId = ref(0);


/**
 * 公司id
 */
let cmpId = 0;

/**
 * 表单
 */
let formData = ref<{
  VideoId: string,
  Title: string,
}>({
  VideoId: "",
  Title: "",
});

/**
 * 表单验证
 */
let rules = reactive({
  Title: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
})

/**
 * 页面展示
 */
function show(videoId: string, _cmpId: number) {
  formData.value.VideoId = videoId;
  cmpId = _cmpId;
  //获取卡券列表
  getData();
  /**
   * 打开页面
   */
  modalViewRef.value.show();
}

/**
 *  保存前校验
 */
function beforeSubmit(): Promise<void> {
  return new Promise((resolve, reject) => {
    formRef.value.validate()
      .then(() => {
        if (!selectEcardId.value) {
          ElMessage.error("请选择要挂载的卡券")
          reject();
          return;
        }
        ElMessageBox.confirm("请一定确认卡券挂载是否正确,每个视频仅有一次挂载机会,一旦确认,无法重新挂载", "系统警告")
          .then(async () => {
            try {
              //生成卡券分享码
              let res = await request("/ECardRule/CreateShare", {
                Id: selectEcardId.value
              })
              // console.log(res.ShareCode);
              //添加挂载
              //http://localhost:39086/DyVideo/MountMicro
              // console.log({
              //   "VideoId": formData.value.VideoId,//视频的video_id
              //   "Title": formData.value.Title,//挂载的标题
              //   "AppUrl": `pages/view/KaQuanLingQu/KaQuanLingQu?sc=${res.ShareCode}`,//挂载的小程序路径
              // })
              await request("/DyVideo/MountMicro", {
                "VideoId": formData.value.VideoId,//视频的video_id
                "Title": formData.value.Title,//挂载的标题
                "AppUrl": `pages/view/KaQuanLingQu/KaQuanLingQu?sc=${res.ShareCode}`,//挂载的小程序路径
                "DocType":"1",
                "DocEntity":res.ShareCode
              })
              ElMessage.success("视频挂载成功");
              emit("submit", {
                videoId: formData.value.VideoId,
                title: formData.value.Title
              })
              resolve();
            } catch (error) {
              reject();
            }
          })
          .catch(reject)
      })
      .catch(reject)
  })
}

/**
 * 关闭页面
 */
function close() {
  emit("close")
}

/**
 * 导出
 */
defineExpose({
  show
})


/**
 * --------------
 *  卡券
 * --------------
 */

let rightLoading = ref(false);

let dataList = ref<ECardRuleDataClass[]>([]);

/**
 * 每页数据数量
 */
let pageSize = ref(25);

/**
 * 库存
 */
let stocksMap = ref<Map<number, number>>(new Map());

/**
 * 搜索内容
 */
let searchValue = ref("");

/**
 * 数据总数量
 */
let dataTotal = ref(0);

/**
 * 当前页数
 */
let currentPage = ref(1);


/**
 * 当点击搜索的时候 
 */
function onSearch() {
  currentPage.value = 1;
  getData();
}

/**
 * 当前页面更新
 */
function onUpdateCurrentPage(count: number) {
  currentPage.value = count;
  //重新加载数据
  getData();
}


/**
 * 获取数据
 */
function getData() {
  selectEcardId.value = 0;
  rightLoading.value = true;
  dataList.value = [];
  queryGet({
    docType: docType,
    actionType: "Usable",
    apiType: "PageList"
  }, {
    Searchv: searchValue.value,
    Start: currentPage.value,
    Limit: pageSize.value,
    Id: cmpId
  })
    .then((res) => {
      dataList.value = res.List.map((item: any) => {
        return new ECardRuleDataClass(item);
      })
      dataTotal.value = res.Total;
      // 获取模板库存
      if (dataList.value.length > 0) getStocks();
    })
    .finally(() => {
      rightLoading.value = false;
    })
}

/**
 * 获取卡券模板库存
 */
function getStocks() {
  stocksMap.value.clear();
  queryGet({
    docType: docType,
    actionType: "Stocks",
    apiType: "SingleList"
  }, {
    Ids: dataList.value.map(item => item.Id),
  })
    .then((res) => {
      for (let item of res) {
        stocksMap.value.set(item.Id, item.UseableStock || 0);
      }
    })
}

/**
 * ====================
 *  页面初始化
 * ====================
 */


</script>

<style lang="less" scoped>
.page-ecard-select {
  filter: drop-shadow(0 0px 3px var(--primaryColor));
}
</style>